package com.hcloud.common.social.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hcloud.common.social.config.SocialRestTemplate;
import com.hcloud.common.social.config.WeixinConfig;
import com.hcloud.common.social.exception.WrongWeixinCodeException;
import com.hcloud.common.social.service.WeixinInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Auther hepangui
 * @Date 2018/12/13
 */
@Service
public class WeixinInfoServiceImpl implements WeixinInfoService {

    private final String INFO_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    @Autowired
    private WeixinConfig weixinConfig;

    @Override
    public String getOpenId(String code) {
        try{
            String result = SocialRestTemplate.getRestTemplate().getForObject(INFO_URL.replace("APPID", weixinConfig.getAppId())
                            .replace("SECRET", weixinConfig.getAppSecret()).replace("CODE", code),
                    String.class
            );
            System.out.println(result);
            Map map = JSONObject.parseObject(result,Map.class);
            String openId = (String)(map.get("openid"));
            if(openId!=null && !"".equals(openId)){
                return openId;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        throw new WrongWeixinCodeException();

    }
}
